package com.yuyou.fn.settlement.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Charsets;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.rocketmq.Producer;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.settlement.entity.PosPayRecord;
import com.yuyou.fn.settlement.service.IPosPayRecordService;
import com.yuyou.fn.settlement.service.IPosPayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.function.Function;

@Service
public class PosPayServiceImpl implements IPosPayService {

    private final static Logger log = LoggerFactory.getLogger(PosPayServiceImpl.class);

    @Resource
    private IPosPayRecordService posPayRecordService ;

    @Resource
    private Producer producer ;

    @Override
    public void savePayRecord(PosPayRecord posPayRecord) {
        posPayRecord.setCreateTime(TimeUtils.now());
        posPayRecord.setUpdateTime(TimeUtils.now());
        posPayRecordService.insertSelective(posPayRecord);
    }

    @Override
    public PosPayRecord findPayRecord(Long requestPayId) {
        return posPayRecordService.findById(requestPayId);
    }

    @Override
    public boolean updateStatus(Long requestPayId, PosPayRecord.STATUS oldStatus, PosPayRecord.STATUS newStatus) {
        return posPayRecordService.updateStatus( requestPayId,  oldStatus,  newStatus);
    }

    @Override
    public void successPay(Long requestPayId,JSONObject posInfo, Function<PosPayRecord, Boolean> callback) {

        if( posPayRecordService.updatePayStatus(requestPayId,posInfo) ){
            PosPayRecord payRecord = posPayRecordService.findById(requestPayId);
            if (!callback.apply(payRecord)) {
                throw new BusException("Fail to callback");
            }
            try{
                producer.send("allin_pay_success", null, JSONObject.toJSONString(payRecord).getBytes(Charsets.UTF_8));
            }catch (Exception e){
                log.error("Send mq fail , topic = allin_pay_success", e );
            }
        }


    }

    @Override
    public boolean isPayingForOrder(Long busOrderId) {
        return posPayRecordService.isPayingForOrder(busOrderId) ;
    }

    @Override
    public boolean isSuccessPay(Long requestPayId) {
        return posPayRecordService.isSuccessPay(requestPayId);
    }

    @Override
    public boolean isLockBalance(Long busOrderId) {
        return posPayRecordService.isLockBalance(busOrderId);
    }

    @Override
    public void cancel(Long busOrderId) {
        posPayRecordService.cancel(busOrderId);
    }
}
